package com.geralt.im.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.geralt.im.commandenum.Code;
import com.geralt.im.controller.Controller;
import com.geralt.im.model.Message;
import com.geralt.im.protocol.Request;
import com.geralt.im.protocol.Response;

public class IMServer {

	public static Map<String, ClientSession> map = new ConcurrentHashMap<String, ClientSession>();
	private boolean isrun;
	private ServerSocket server;
	private long StartTime;

	public void runServer() {
		System.out.println("run server");

		try {
			if (server == null)
				server = new ServerSocket(10102);
			while (isrun) {
				Socket socket = server.accept();
				ClientSession session = new JsonClientSession(socket);
				new Thread(session).start();
			}
		} catch (Exception e) {
			System.out.println("ServerSocket closed");
		}
	}

	public boolean isRun() {
		return isrun;
	}

	public void setIsrun(boolean isrun) {
		this.isrun = isrun;
	}

	public void start() {
		System.out.println("server start");
		this.StartTime = System.currentTimeMillis();
		isrun = true;
		new Thread(new Runnable() {
			@Override
			public void run() {
				runServer();
			}
		}).start();
	}

	public void stop() {
		System.out.println("server stop");
		Response response = new Response();
		response.setStatusCode(Code.BAD_REQUEST);
		response.setType("SEND");
		Message message= new Message();
		message.setContent("shutdown");
		response.getParameter().put("MESSAGE",message);
		isrun = false;
		for (String id : map.keySet()) {
			map.get(id).send(response);
			map.get(id).setRun(false);
			map.get(id).close();
			System.out.println("map +"+id+":"+map.get(id).socket.isClosed());
		}
		map.clear();
		try {
			server.close();
			server = null;
		} catch (IOException e) {
			System.out.println("server is closed");
		}
	}

	public long getStartTime() {
		return StartTime;
	}

	public void setStartTime(long startTime) {
		StartTime = startTime;
	}
}
